import WebHeader from '@/www/components/WebHeader'
import WebFooter from '@/www/components/WebFooter'
import { getQuote, uploadFile, postQuoteOrder } from '@/apiv2/quote'

const CODE = 'JointSheet'

export default {
  components: { WebHeader, WebFooter },
  data() {
    return {
      quoteData: undefined,
      checkValue: {
        flagAddCover: false,//加封面
        flagPrintCover: false,//印封面
        flagPinholeThreads: false,//打针孔线
        flagNumber: false,//打号码
        flagDirection: true,//胶装方向
        flagCardBoard: false,//垫纸板
      },

      quoteValue: {
        category: undefined,
        color: undefined,
        direction: '左边',
        customQuantity: undefined,
        style: 1,
        quantity: undefined,
        size: undefined,
      },

      directionOptions: [
        {label: '左边',value:'左边'},
        {label: '上边',value:'上边'}
      ],

      user: undefined,
      quote: undefined,
      quoteList: undefined,
      detail: undefined,
      fileList: [],
      postData: {
        quantity: undefined,
        detail: undefined,
        amount: undefined,
        fileIds: undefined
      },
      note: undefined
    }
  },

  created(){
    const user = JSON.parse(localStorage.getItem('user'))
    this.user = user

    getQuote(CODE).then(res => {
      let quoteData = res.config
      this.quoteValue.category = quoteData.cateData.list[0]
      this.quoteValue.size = quoteData.sizeData.list[0]
      this.quoteValue.quantity = quoteData.stepData.list[0]
      this.quoteValue.color = quoteData.colorData.list[0]
      this.quoteData = quoteData
    })
  },

  methods: {

    selectQuantity(){
      if(this.quoteValue.quantity){
        this.quoteValue.customQuantity = undefined
      }
    },
    customQuantity(){
      if(this.quoteValue.customQuantity){
        this.quoteValue.quantity = undefined
      }else{
        this.quoteValue.quantity = this.quoteData.stepData.list[0]
      }
    },

    syncCheck(name,target){
      if(this.checkValue[name]){
        this.checkValue[target] = true
      }
    },

    offCheck(name,target){
      if(!this.checkValue[name]){
        this.checkValue[target] = false
      }
    },

    getQuote(){
      let detail = ''
      let cardBoardPrice = undefined
      let {quoteData,quoteValue,checkValue,postData} = this

      detail += '尺寸' + quoteValue.size +'，'
        + quoteValue.category +'，'
        + quoteValue.style + '款，'

      if(true){
        let area = parseInt(quoteValue.size.split('*')[0]) * parseInt(quoteValue.size.split('*')[1])
        let area2 = parseInt(quoteData.process.cardBoardValue.split('*')[0]) * parseInt(quoteData.process.cardBoardValue.split('*')[1])
        cardBoardPrice = area >= area2 ? quoteData.process.cardBoardPriceLessThan : quoteData.process.cardBoardPriceLargeThan
      }

      if(checkValue.flagAddCover){
        detail += '加封面，'
      }

      if(checkValue.flagPrintCover){
        detail += '印封面(单色)，'
      }

      if(checkValue.flagPinholeThreads){
        detail += '打针孔线，'
      }

      if(checkValue.flagNumber){
        detail += '打号码，'
      }

      if(checkValue.flagDirection){
        detail += quoteValue.direction + '胶装，'
      }

      if(checkValue.flagCardBoard){
        detail += '加垫纸板'
      }

      let quoteList = []

      let finalQantity = this.quoteValue.quantity ? parseInt(this.quoteValue.quantity) : parseInt(this.quoteValue.customQuantity)
      detail += finalQantity + '本'

      let defaultFlag = false

      let stepList = []

      postData.detail = detail

      quoteData.stepData.list.forEach(i => {
        const QTY = parseInt(i)//阶梯数量
        stepList.push(QTY)
        let priceItem = undefined
        for(let i=0;i<quoteData.skuList.length;i++){
          let item = quoteData.skuList[i]
          if(item.name == quoteValue.category && QTY == parseInt(item.quantity) && item.color == quoteValue.color && item.size == quoteValue.size){
            priceItem = item
          }
        }

        const MATERIAL_AMOUNT = parseInt(priceItem.price) * parseInt(quoteValue.style)

        let processAmount = 0

        if(checkValue.flagPrintCover){
          let {coverStart,coverFeePerAdd100} = quoteData.process
          processAmount += parseFloat((QTY-50)/100) * parseFloat(coverFeePerAdd100) + parseFloat(coverStart)
        }

        if(checkValue.flagPinholeThreads){
          let {pinholeThreads,pinholeThreadsAddPer100} = quoteData.process
          processAmount += parseFloat((QTY-50)/100) * parseFloat(pinholeThreadsAddPer100) + parseFloat(pinholeThreads)
        }

        if(checkValue.flagCardBoard){
          processAmount += parseFloat(cardBoardPrice) * parseFloat(QTY)
        }

        processAmount = parseInt(processAmount) * parseInt(quoteValue.style)

        const AMOUNT = parseInt(MATERIAL_AMOUNT) + processAmount


        if(parseInt(quoteValue.quantity) == parseInt(i)){
          postData.amount = AMOUNT
          defaultFlag = true
        }

        quoteList.push({
          quantity: QTY,
          materialAmount: parseInt(MATERIAL_AMOUNT),
          processAmount: parseInt(processAmount),
          totalAmount: AMOUNT

        })

        this.quoteList = quoteList
      })

      if(!defaultFlag){
        let target = parseInt(finalQantity)
        let farr = []
        for(let i=(stepList.length-1);i > -1;i--){
          if(target < stepList[i]){
            continue
          }
          let m = target % stepList[i]
          farr.push({
            quantity: stepList[i],
            count: parseInt(target / stepList[i])
          })
          if(m == 0){
            break
          }else{
            target = m
          }
        }

        let finalMaterialAmount = 0
        let finalProcessAmount = 0
        let index = undefined
        for(let i=0;i<quoteList.length;i++){
          let item = quoteList[i]
          for(let j=0;j<farr.length;j++){
            if(item.quantity == farr[j].quantity){
              if(!index){
                index = i
              }
              finalMaterialAmount += item.materialAmount * farr[j].count
              finalProcessAmount += item.processAmount * farr[j].count
            }
          }
        }
        quoteList.splice(index + 1,0,{
          quantity: finalQantity,
          materialAmount: parseInt(finalMaterialAmount),
          processAmount: parseInt(finalProcessAmount),
          totalAmount: parseInt(finalMaterialAmount) + parseInt(finalProcessAmount)
        })
        postData.amount = parseInt(finalMaterialAmount) + parseInt(finalProcessAmount)
        this.quoteList = quoteList
        this.postData = postData
      }

    },

    submitOrder(){
      const {fileList,postData} = this

      if(fileList.length < 1){
        this.$message.error('请上传设计稿')
        return
      }

      let fileIds = [];
      fileList.forEach(item => {
        fileIds.push(item.id)
      })
      postData.fileIds = fileIds

      const loading = this.$loading({
        lock: true,
        text: '正在创建订单',
        spinner: 'el-icon-loading',
        background: 'rgba(0,0,0,0.7)'
      });

      postQuoteOrder(postData).then(res => {
        loading.close()
        this.$message.success('成功创建订单')
        this.$router.push({
          path: '/submitOrder',
          query: { id : res.id}
        })
      }).catch(err => {
        loading.close()
        this.$message.error('创建订单失败')
      })
    },

    handleUpload: async function(data){
      const formData = new FormData()
      formData.append('file', data.file)
      const res = await uploadFile(formData)
      let fileList = this.fileList
      fileList.push(res.file)
      this.fileList = fileList
      console.log(fileList)
    },
  }
}
